#include<iostream>
#include<signal.h>
#include<unistd.h>
#include<sys/types.h>
#include<sys/wait.h>
using namespace std;
//volatile int cnt=0;
int cnt=0;
void printpending(sigset_t block)
{
    cout<<getpid()<<":";
    for(int i=31;i>=1;i--)
    {
        if(sigismember(&block,i))
        {
            cout<<"1";
        }
        else
        {
            cout<<"0";
        }
    }
    cout<<endl;
}
void handler(int sig)
{
    cout<<"Signal received:"<<sig<<endl;
    int cnt1=3;
    /*
    while(1)
    {
        sigset_t pending;
        sigpending(&pending);
        printpending(pending);
        sleep(1);
    }
    */
    cnt=1;
}
//////////
void child(int sig)
{
    while(1)
    {
        pid_t n=waitpid(-1,NULL,WNOHANG);
        if(n==0)
        {
            break;
        }
        else
        {
            cout<<"Child process error"<<endl;
            break;
        }
    }
}
/*
int main()
{
    signal(SIGCHLD,child);
    for(int i=0;i<10;i++)
    {
        pid_t pid=fork();
        if(pid<0)
        {
            cout<<"Fork error"<<endl;
            return 1;
        }
        else if(pid==0)
        {
            //child process
            cout<<"Child process"<<endl;
            sleep(1);
            exit(1);   
            if(i<=3)
            {
                exit(3);
            }
            else{
                pause();
            }
        }
    }
    while(1)
    {
        cout<<"Father process"<<endl;
        sleep(1);
    }
    return 0;
}*/
/////////
///////////////////////
//volatile关键字

int main()
{
    signal(SIGINT,handler);
    while(!cnt)
    {
        cout<<"Hello,world"<<endl;
        sleep(1);
    }
    return 0;
}
//////////

/*int main()
{
    //更高效的signal函数：sigaction
    struct sigaction act;
    act.sa_handler=handler;
    sigset_t block;
    sigemptyset(&block);
    for(int i=1;i<32;i++)
    {
        if(i==SIGINT)
        {
            continue;
        }
        sigaddset(&block,i);//把信号屏蔽掉
    }
    sigemptyset(&act.sa_mask);
    act.sa_mask=block;
    sigaction(SIGINT,&act,NULL);
    while(1)
    {
        sigset_t pending;
        sigpending(&pending);
        printpending(pending);
        sleep(1);
    }
    return 0;
}*/